import './Scss/MixingStation.scss'
import './MixingStation.scss'
import { Column, Gauge } from '@ant-design/plots'
import { useEffect, useRef, useState } from 'react'
import { Http } from '../../../../Common/Api'
import { useSize, useRequest, useLatest, useMount } from 'ahooks'
import { TitleSmall001 } from '../Common/SmallTitle'
import { WebTemplateUrl } from './configuration'
import { FrontModalBox } from '../Modal'

import {
    ColumnConfigA01Template,
    AreaA01Template,
    DualAxesA1Template,
    ColumnStyle,
    GaugeA01Template,
} from './AssetsCharts'

import { CaretUpOutlined, CaretDownOutlined } from '@ant-design/icons'

const { hostname } = window.location

const Data = [
    {
        uuid: 1,
        label: '沥青拌合站',
        color: 'rgb(241, 214, 130)',
        title: '沥青产量 (kg)',
        charts: 9,
        type: 'AsphaltMixingStationDetail',
        typeTow: 'GettAsphaltMixingStationDetail',
        child: [
            { uuid: 1, label: '出料温度预警', img: 'ba005.png', value: 'temperature' },
            { uuid: 2, label: '油石比预警', img: 'ba003.png', value: 'asphaltratio' },
            { uuid: 3, label: '4.75mm通过率', charts: 'sieve475' },
        ],
    },
    {
        uuid: 2,
        label: '水泥拌合站',
        color: 'rgb(130, 224, 241)',
        title: '水泥产量 (m³)',
        charts: 8,
        type: 'CementMixingStationExceededDatil',
        typeTow: 'CementMixingStationGroupDetail',
        child: [
            { uuid: 1, img: 'ba001.png' },
            { uuid: 2, label: '水泥用量预警', img: 'ba003.png', value: 'cement' },
            { uuid: 3, label: '水胶比', charts: 'waterbinderratio' },
        ],
    },
]

const GaugeChartsSetUp = percent => {
    return {
        autoFit: false,
        height: 120,
        width: 220,
        percent,
        radius: 0.9,
        startAngle: Math.PI,
        endAngle: 2 * Math.PI,
        range: { color: ['l(0) 0:#F28159 1:#ADEEBA', 'rgba(58, 168, 226, 0.2)'], width: 27 },
        indicator: null,
        statistic: {
            title: {
                offsetY: 0,
                style: { fontSize: '50px', color: '#fff', fontWeight: 'bold', fontFamily: 'Bahnschrift' },
                formatter: ({ percent }) => ` ${(percent * 100).toFixed(0)}%`,
            },
        },
        gaugeStyle: { lineCap: 'round' },
    }
}

const ColumnCharts = (size, data) => {
    const { width, height } = size
    return {
        autoFit: false,
        width,
        height,
        maxColumnWidth: 14,
        appendPadding: 24,
        data,
        isGroup: true,
        xField: 'type',
        yField: 'value',
        seriesField: 'name',
        color: ['#B2FBFD', '#FAD688'],
        legend: {
            layout: 'horizontal',
            position: 'top-right',
            offsetY: 24,
            itemName: { style: { fill: '#B2FBFD', fontSize: 12 } },
        },
        xAxis: {
            label: { style: { fill: '#B2FBFD' } },
            line: { style: { stroke: '#B2FBFD' } },
            tickLine: { style: { stroke: '#B2FBFD' } },
        },
        yAxis: {
            title: { text: '', position: 'end', autoRotate: false, offset: 50, style: { fill: '#B2FBFD' } },
            tickCount: 5,
            label: { style: { fill: '#B2FBFD' } },
            grid: { line: { style: { stroke: 'rgba(178, 251, 253, 0.2)', lineDash: [8, 2] } } },
        },
        scrollbar: {
            type: 'horizontal',
            categorySize: 200,
            style: {
                thumbColor: 'rgba(0, 60, 200, 0.4)',
                trackColor: 'rgba(0, 0, 0, 0.4)',
                thumbHighlightColor: 'rgba(0, 60, 200, 1)',
            },
        },
    }
}

export const MixingStation001 = () => {
    const ChartsBox = useRef()
    const size = useSize(ChartsBox)

    const [DataOne, setDataOne] = useState()
    const [ChartsOne, setChartsOne] = useState()
    const [ChartsTwo, setChartsTwo] = useState()

    const [OptionsCall, setOptionsCall] = useState()

    const { runAsync } = useRequest(Http, { manual: true, onSuccess: res => setDataOne(res) })
    // 水泥
    const { run: InfoByOrg8 } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            let data = []
            res.list.forEach(({ tableName, planCementConcrete, quantityAct, uuid, per }) => {
                data = [
                    ...data,
                    { name: '实际产量', type: tableName, value: quantityAct, uuid },
                    { name: '计划产量', type: tableName, value: planCementConcrete, uuid },
                ]
            })
            setChartsOne(data)
        },
    })
    // 沥青
    const { run: InfoByOrg9 } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            let data = []
            res.list.forEach(({ tableName, planBitulith, quantityAct, uuid, per }) => {
                data = [
                    ...data,
                    { name: '实际产量', type: tableName, value: quantityAct, uuid },
                    { name: '计划产量', type: tableName, value: planBitulith, uuid },
                ]
            })
            setChartsTwo(data)
        },
    })

    useEffect(() => {
        runAsync({ url: 'getExceededGroupInfo' })

        if (hostname.includes('jszx')) {
            InfoByOrg8({ url: `getCementMixingStationGroupInfo` })
            InfoByOrg9({ url: `getAsphaltMixingStationGroupInfo` })
        } else {
            InfoByOrg8({ url: `getGetCementMixingStationGroupInfoByOrg`, data: { OrganizationGroupCode: 8 } })
            InfoByOrg9({ url: `getAsphaltMixingStationGroupInfoByOrg`, data: { OrganizationGroupCode: 9 } })
        }
    }, [InfoByOrg8, InfoByOrg9, runAsync])
    return (
        <div className="MixingStation001">
            {DataOne &&
                Data.map(({ uuid, label, title, color, charts, type, typeTow, child }) => (
                    <div key={uuid} className="Box">
                        <div>{label}</div>
                        <div style={{ color }}>
                            {child.map(({ uuid, img, label, charts, value }) => (
                                <div
                                    key={uuid}
                                    onClick={() => {
                                        if (label) {
                                            setOptionsCall({
                                                type: 'TableList',
                                                data: { title: `${label}明细`, type, uuid: value || charts },
                                            })
                                        }
                                    }}
                                >
                                    {charts && (
                                        <div className="Charts">
                                            <Gauge {...GaugeChartsSetUp(Number(DataOne[charts]))} />
                                        </div>
                                    )}
                                    {img && <img src={WebTemplateUrl + img} alt="" />}
                                    {label && <div className="Lable">{label}</div>}
                                    {label && !charts && <div className="Number">{Number(DataOne[value])}</div>}
                                </div>
                            ))}
                        </div>
                        <TitleSmall001 title={title} />
                        <div ref={ChartsBox}>
                            {size && ChartsOne && ChartsTwo && (
                                <Column
                                    {...ColumnCharts(size, charts === 8 ? ChartsOne : ChartsTwo)}
                                    onReady={plot =>
                                        plot.on('plot:click', e => {
                                            const { x, y } = e
                                            const [{ data }] = plot.chart.getTooltipItems({ x, y })
                                            setOptionsCall({
                                                type: 'TableList',
                                                data: {
                                                    title: charts === 8 ? '水泥拌合站生产明细' : '沥青拌合站生产明细',
                                                    type: typeTow,
                                                    uuid: data?.uuid,
                                                },
                                            })
                                        })
                                    }
                                />
                            )}
                        </div>
                    </div>
                ))}
            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

export const MixingStation002 = () => {
    const ChartsBox = useRef()
    const size = useSize(ChartsBox)
    const [DataOne, setDataOne] = useState()
    const [ChartsOne, setChartsOne] = useState()
    const [ChartsTwo, setChartsTwo] = useState()
    const [OptionsCall, setOptionsCall] = useState()
    const { runAsync } = useRequest(Http, { manual: true, onSuccess: res => setDataOne(res) })
    // 水泥
    const { run: InfoByOrg8 } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            let data = []
            res.list.forEach(({ tableName, planCementConcrete, quantityAct, uuid, per }) => {
                data = [
                    ...data,
                    { name: '实际产量', type: tableName, value: quantityAct, uuid },
                    { name: '计划产量', type: tableName, value: planCementConcrete, uuid },
                ]
            })
            setChartsOne(data)
        },
    })
    // 沥青
    const { run: InfoByOrg9 } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            let data = []
            res.list.forEach(({ tableName, planBitulith, quantityAct, uuid, per }) => {
                data = [
                    ...data,
                    { name: '实际产量', type: tableName, value: quantityAct, uuid },
                    { name: '计划产量', type: tableName, value: planBitulith, uuid },
                ]
            })
            setChartsTwo(data)
        },
    })

    const [Active, setActive] = useState(1)
    const [Status, setStatus] = useState(false)

    const ActiveLatest = useLatest(Active)
    useEffect(() => {
        runAsync({ url: 'getExceededGroupInfo' })
        if (hostname.includes('jszx')) {
            InfoByOrg8({ url: `getCementMixingStationGroupInfo` })
            InfoByOrg9({ url: `getAsphaltMixingStationGroupInfo` })
        } else {
            InfoByOrg8({ url: `getGetCementMixingStationGroupInfoByOrg`, data: { OrganizationGroupCode: 8 } })
            InfoByOrg9({ url: `getAsphaltMixingStationGroupInfoByOrg`, data: { OrganizationGroupCode: 9 } })
        }
    }, [InfoByOrg8, InfoByOrg9, runAsync])

    const onClick = uuid => {
        const { charts, typeTow: type } = Data.find(v => v.uuid === ActiveLatest.current)
        const title = charts === 8 ? '水泥拌合站生产明细' : '沥青拌合站生产明细'
        setOptionsCall({ type: 'TableList', data: { title, type, uuid } })
    }

    if (DataOne) {
        return (
            <div className="MixingStation002">
                <div className="Nav" onClick={() => setStatus(e => !e)}>
                    {Data.find(v => v.uuid === Active).label}
                    {Status ? <CaretUpOutlined /> : <CaretDownOutlined />}
                    {Status && (
                        <div>
                            {Data.map(({ uuid, label }) => (
                                <div
                                    key={uuid}
                                    onClick={() => setActive(uuid)}
                                    className={Active === uuid ? 'active' : ''}
                                >
                                    {label}
                                </div>
                            ))}
                        </div>
                    )}
                </div>
                <div className="Box">
                    <div className="Image">
                        <div>
                            <img src={WebTemplateUrl + Data.find(v => v.uuid === Active).child[0].img} alt="" />
                            <div>{DataOne[Data.find(v => v.uuid === Active).child[0].value]}</div>
                            <div>{Data.find(v => v.uuid === Active).child[0].label}</div>
                        </div>
                        <div>
                            <img src={WebTemplateUrl + Data.find(v => v.uuid === Active).child[1].img} alt="" />
                            <div>{DataOne[Data.find(v => v.uuid === Active).child[1].value]}</div>
                            <div>{Data.find(v => v.uuid === Active).child[1].label}</div>
                        </div>
                    </div>
                    <div className="Charts">
                        <Gauge
                            {...GaugeChartsSetUp(Number(DataOne[Data.find(v => v.uuid === Active).child[2].charts]))}
                        />
                        <div>{Data.find(v => v.uuid === Active).child[2].label}</div>
                    </div>
                </div>
                <TitleSmall001 title={Data.find(v => v.uuid === Active).label} />
                <div className="Charts" ref={ChartsBox}>
                    {size &&
                        ChartsOne &&
                        ChartsTwo &&
                        (() => {
                            const { charts } = Data.find(v => v.uuid === ActiveLatest.current)
                            const data = charts === 8 ? ChartsOne : ChartsTwo
                            return (
                                <Column
                                    {...ColumnCharts(size, data)}
                                    onReady={plot =>
                                        plot.on('plot:click', e => {
                                            const { x, y } = e
                                            const [{ data }] = plot.chart.getTooltipItems({ x, y })
                                            onClick(data?.uuid)
                                        })
                                    }
                                />
                            )
                        })()}
                </div>
                <FrontModalBox OptionsCall={OptionsCall} />
            </div>
        )
    }
}

// TitleSmall001
export const AsphaltMixingStationDetailTempA01 = ({ OrgEvent }) => {
    const ChartBox = useRef()
    const size = useSize(ChartBox)
    const styleA01 = {
        color: 'rgba(68, 255, 244, 1)',
        ColumnColor: 'l(270) 0:rgba(204, 248, 255, 1) 1:rgba(204, 248, 255, 0.4)',
        ColumnWidth: 16,
        ColumnLegend: true,
        LegendPossion: 'top-right',
        LegendoffsetY: 10,
        Legendfill: '#B2FBFD',
        LegendfontSize: 12,
        XLine: '#B2FBFD',
        XLabel: '#B2FBFD',
        XTick: '#B2FBFD',
        YTitle: '℃',
        YTColor: '#B2FBFD',
        YPosi: 'end',
        YAuto: true,
        YOffset: 50,
        YColoc: '#B2FBFD',
        YNumber: 5,
        YGrid: 'rgba(155, 253, 255, 0.35)',
        BarStatus: false,
        BarHeight: 8,
        BarWidth: 80,
        BarTrack: 'rgba(178, 251, 253, 0.2)',
        BarThumb: 'rgba(178, 251, 253, 1)',
        BarHover: '#367EF2',
        isStack: true,
        isGroup: true,
    }

    const styleA02 = {
        color: 'rgba(68, 255, 244, 1)',
        ColumnColor: 'l(270) 0:rgba(204, 248, 255, 1) 1:rgba(204, 248, 255, 0.4)',
        ColumnWidth: 16,
        ColumnLegend: true,
        LegendPossion: 'top-right',
        LegendoffsetY: 10,
        Legendfill: '#B2FBFD',
        LegendfontSize: 12,
        XLine: '#B2FBFD',
        XLabel: '#B2FBFD',
        XTick: '#B2FBFD',
        YTitle: '℃',
        YTColor: '#B2FBFD',
        YPosi: 'end',
        YAuto: true,
        YOffset: 50,
        YColoc: '#B2FBFD',
        YNumber: 5,
        YGrid: 'rgba(155, 253, 255, 0.35)',
        BarStatus: false,
        BarHeight: 8,
        BarWidth: 80,
        BarTrack: 'rgba(178, 251, 253, 0.2)',
        BarThumb: 'rgba(178, 251, 253, 1)',
        BarHover: '#367EF2',
        isStack: true,
        isGroup: true,

        value: '出料总量',
        count: '出料总次',
    }

    const styleA03 = {
        ColumnColor:
            'l(180) 0:rgba(255, 218, 138, 1) 1:rgba(255, 218, 138, 0.4)&l(180) 0:rgba(199, 255, 239, 1) 1:rgba(199, 255, 239, 0.4)&l(90) 0:rgba(152, 179, 255, 1) 1:rgba(152, 179, 255, 0.4)&l(90) 0:rgba(0, 133, 88, 1) 1:rgba(0, 133, 88, 0.4)',
        ColumnWidth: 16,
        ColumnLegend: true,
        LegendPossion: 'top-right',
        LegendoffsetY: 10,
        Legendfill: '#B2FBFD',
        LegendfontSize: 12,
        XLine: '#B2FBFD',
        XLabel: '#B2FBFD',
        XTick: '#B2FBFD',
        YTitle: 'kg',
        YTColor: '#B2FBFD',
        YPosi: 'end',
        YAuto: true,
        YOffset: 50,
        YColoc: '#B2FBFD',
        YNumber: 5,
        YGrid: 'rgba(155, 253, 255, 0.35)',
        BarStatus: false,
        BarHeight: 8,
        BarWidth: 80,
        BarTrack: 'rgba(178, 251, 253, 0.2)',
        BarThumb: 'rgba(178, 251, 253, 1)',
        BarHover: '#367EF2',
        isStack: true,
        isGroup: true,
    }

    const [ChartDataA01] = useState([
        { name: '温度', type: '02:00', value: Math.floor(Math.random() * 100) + 1 },
        { name: '温度', type: '04:00', value: Math.floor(Math.random() * 100) + 1 },
        { name: '温度', type: '06:00', value: Math.floor(Math.random() * 100) + 1 },
        { name: '温度', type: '08:00', value: Math.floor(Math.random() * 100) + 1 },
        { name: '温度', type: '10:00', value: Math.floor(Math.random() * 100) + 1 },
        { name: '温度', type: '12:00', value: Math.floor(Math.random() * 100) + 1 },
    ])

    const [ChartDataA02] = useState([
        { type: '00:00', 出料总量: Math.floor(Math.random() * 100) + 1, 出料总次: Math.floor(Math.random() * 100) + 1 },
        { type: '03:00', 出料总量: Math.floor(Math.random() * 100) + 1, 出料总次: Math.floor(Math.random() * 100) + 1 },
        { type: '06:00', 出料总量: Math.floor(Math.random() * 100) + 1, 出料总次: Math.floor(Math.random() * 100) + 1 },
        { type: '09:00', 出料总量: Math.floor(Math.random() * 100) + 1, 出料总次: Math.floor(Math.random() * 100) + 1 },
        { type: '12:00', 出料总量: Math.floor(Math.random() * 100) + 1, 出料总次: Math.floor(Math.random() * 100) + 1 },
        { type: '15:00', 出料总量: Math.floor(Math.random() * 100) + 1, 出料总次: Math.floor(Math.random() * 100) + 1 },
        { type: '18:00', 出料总量: Math.floor(Math.random() * 100) + 1, 出料总次: Math.floor(Math.random() * 100) + 1 },
        { type: '21:00', 出料总量: Math.floor(Math.random() * 100) + 1, 出料总次: Math.floor(Math.random() * 100) + 1 },
    ])

    const [ChartDataA03] = useState([
        { name: '总量', type: '沥青', value: Math.floor(Math.random() * 100) + 1 },
        { name: '总量', type: '骨料1', value: Math.floor(Math.random() * 100) + 1 },
        { name: '总量', type: '骨料2', value: Math.floor(Math.random() * 100) + 1 },
        { name: '总量', type: '骨料3', value: Math.floor(Math.random() * 100) + 1 },
        { name: '总量', type: '骨料4', value: Math.floor(Math.random() * 100) + 1 },
        { name: '总量', type: '骨料5', value: Math.floor(Math.random() * 100) + 1 },
        { name: '总量', type: '骨料6', value: Math.floor(Math.random() * 100) + 1 },
        { name: '总量', type: '水泥', value: Math.floor(Math.random() * 100) + 1 },
        { name: '总量', type: '矿粉', value: Math.floor(Math.random() * 100) + 1 },
        { name: '总量', type: '再生料', value: Math.floor(Math.random() * 100) + 1 },
    ])

    const [ChartDataA04] = useState([
        { name: '油石比', type: '02:00', value: Math.floor(Math.random() * 100) + 1 },
        { name: '油石比', type: '04:00', value: Math.floor(Math.random() * 100) + 1 },
        { name: '油石比', type: '06:00', value: Math.floor(Math.random() * 100) + 1 },
        { name: '油石比', type: '08:00', value: Math.floor(Math.random() * 100) + 1 },
        { name: '油石比', type: '10:00', value: Math.floor(Math.random() * 100) + 1 },
        { name: '油石比', type: '12:00', value: Math.floor(Math.random() * 100) + 1 },
    ])

    return (
        <div className="AsphaltMixingStationDetailTempA01">
            <div className="Right">
                <div className="Top">
                    <div className="left">
                        <TitleSmall001 title="温度分析" />
                        <div className="Charts" ref={ChartBox}>
                            {size && <AreaA01Template data={ChartDataA01} size={size} style={styleA01} />}
                        </div>
                    </div>
                    <div className="right">
                        <TitleSmall001 title="出料情况" />
                        <div className="Charts">
                            {size && <DualAxesA1Template data={ChartDataA02} size={size} style={styleA02} />}
                        </div>
                    </div>
                </div>
                <div className="Btm">
                    <div className="left">
                        <TitleSmall001 title="当天骨料实际用料总量" />
                        <div className="Charts">
                            {size && <ColumnConfigA01Template data={ChartDataA03} size={size} style={styleA03} />}
                        </div>
                    </div>
                    <div className="right">
                        <TitleSmall001 title="油石比分析" />
                        <div className="Charts">
                            {size && <AreaA01Template data={ChartDataA04} size={size} style={styleA01} />}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

const MixingStationA01Mapping = {
    1: {
        label: '沥青拌合站',
        url: 'getAsphaltMixingStationGroupInfoByOrg',
        mapping: { type: 'tableName', value1: 'quantityAct', value2: 'planBitulith' },
        type: 'AsphaltMixingStationDetail',
        typeTow: 'GettAsphaltMixingStationDetail',
        list: [
            { uuid: 1, label: '出料温度预警', img: 'ba005.png', value: 'temperature' },
            { uuid: 2, label: '油石比预警', img: 'ba003.png', value: 'asphaltratio' },
            { uuid: 3, label: '4.75mm通过率', charts: 'sieve475' },
        ],
    },
    2: {
        label: '水泥拌合站',
        url: 'getGetCementMixingStationGroupInfoByOrg',
        mapping: { type: 'tableName', value1: 'quantityAct', value2: 'planCementConcrete' },
        type: 'CementMixingStationExceededDatil',
        typeTow: 'CementMixingStationGroupDetail',
        list: [
            { uuid: 1, img: 'ba001.png' },
            { uuid: 2, label: '水泥用量预警', img: 'ba003.png', value: 'cement' },
            { uuid: 3, label: '水胶比', charts: 'waterbinderratio' },
        ],
    },
}

export const MixingStationA01 = ({ type, title, charts }) => {
    const { label, url, list, mapping } = MixingStationA01Mapping[type]

    const ChartBox = useRef()
    const size = useSize(ChartBox)

    const [Data, setData] = useState({
        temperature: '0.0',
        asphaltratio: '0.0',
        sieve475: '0.0',
        cement: '0.0',
        waterbinderratio: '0.0',
    })

    const [Charts, setCharts] = useState()

    const { runAsync: GetA01 } = useRequest(Http, { manual: true, onSuccess: res => setData(res) })
    const { runAsync: GetA02 } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            const { type, value1, value2 } = mapping
            let data = []
            res.list.forEach(item => {
                data = [
                    ...data,
                    { name: '实际产量', type: item[mapping[type]], value: item[mapping[value1]], uuid: item.uuid },
                    { name: '计划产量', type: item[mapping[type]], value: item[mapping[value2]], uuid: item.uuid },
                ]
            })
            setCharts(data)
        },
    })

    useMount(() => {
        GetA01({ url: 'getExceededGroupInfo' })
        GetA02({ url, data: { OrganizationGroupCode: charts } })
    })

    return (
        <div className="MixingStationA01">
            <div className="Title">{label}</div>
            <div className="Top">
                {list.map(({ uuid, label, img, value, charts }) => (
                    <div key={uuid}>
                        {img && (
                            <>
                                <img src={WebTemplateUrl + img} alt="" />
                                {label && (
                                    <>
                                        <div className="value">{Data[value]}</div>
                                        <div className={`label ${type === '1' ? 'A01' : 'A02'}`}>{label}</div>
                                    </>
                                )}
                            </>
                        )}
                        {charts && (
                            <>
                                <GaugeA01Template
                                    size={{ width: 240, height: 140 }}
                                    data={Data[value] / 100 || 0}
                                    title=" "
                                />
                                <div className={`label ${type === '1' ? 'A01' : 'A02'}`}>{label}</div>
                            </>
                        )}
                    </div>
                ))}
            </div>
            <div className="Btm">
                <TitleSmall001 title={title} />
                <div className="Charts" ref={ChartBox}>
                    {size && Charts && <ColumnConfigA01Template data={Charts} size={size} style={ColumnStyle} />}
                </div>
            </div>
        </div>
    )
}
